import {
  CanActivate,
  ExecutionContext,
  HttpException,
  Injectable,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { AuthorityService } from '../services/authority.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly authorityService: AuthorityService) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = request.headers.token;
    if (token) {
      // token验证
      const result = this.authorityService
        .verify(token)
        .then((res) => {
          return res ? true : false;
        })
        .catch(() => {
          throw new HttpException('老铁，你这token怕是有毛病吧', 401);
        });
      return result;
    } else {
      throw new HttpException('token值为空', 422);
    }
  }
}
